class Solution {
    //不用去重，更简单，直接diff和newdiff更新比较就行
    public int threeSumClosest(int[] nums, int target) {
        int n = nums.length;
        Arrays.sort(nums);

        int sum = nums[0]+nums[1]+nums[2];
        int ret = sum;
        int diff = Math.abs(sum-target);

        for(int i=0;i<n-2;i++) {
            int l = i+1;
            int r = n-1;
            while(l<r) {
                sum = nums[i]+nums[l]+nums[r];
                int newDiff = Math.abs(sum-target);
                //更新结果            
                if(newDiff < diff) {
                    ret = sum;
                    diff = newDiff;
                }
                //差值为0，直接返回
                if(sum == target) return ret;
                else if(sum < target) l++;
                else r--;
            }
        }
        return ret;
    }
}